#import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
#import "TalkingDataSDK.h"
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate ()<UNUserNotificationCenterDelegate>
{
    FlutterMethodChannel *_channel;
}

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [GeneratedPluginRegistrant registerWithRegistry:self];
    
    FlutterViewController *vc = (FlutterViewController *)self.window.rootViewController;
    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"massage_channel" binaryMessenger:vc.binaryMessenger];
    _channel = channel;
    
    [channel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
        if([call.method isEqualToString:@"tdid"]){
            result([TalkingDataSDK getDeviceId]);
        }
        
        if([call.method isEqualToString:@"buryingPoint"]){
            NSString *label = call.arguments[@"task_label"];
            NSString *title = call.arguments[@"task_title"];
            if(label == nil){
                label = @"";
            }
            if(title == nil){
                title = @"";
            }
            [TalkingDataSDK onEvent:title parameters:@{@"task_label":label}];
        }
        
        if([call.method isEqualToString:@"initTDSDK"]){
            [TalkingDataSDK init:@"F398F4D89EE54977AAE4F3A4195D3DD8" channelId:@"AppStore" custom:@""];
        }
    }];
    
    [self registApns:application];
    
    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (void)registApns:(UIApplication *)application{
    // 注册远程通知
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [application registerForRemoteNotifications];
            });
        }
    }];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // 将设备令牌发送到服务器进行注册
    NSString *token = [self hexadecimalStringFromData:deviceToken];
    NSLog(@"Device Token: %@", token);
    [_channel invokeMethod:@"deviceToken" arguments:token];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Failed to register for remote notifications: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    // 处理接收到的远程通知
    NSLog(@"Received remote notification: %@", userInfo);
    
    [_channel invokeMethod:@"parseScheme" arguments:userInfo];
    
    // 完成处理
    completionHandler(UIBackgroundFetchResultNewData);
}

- (NSString *)hexadecimalStringFromData:(NSData *)data {
    NSUInteger capacity = data.length * 2;
    NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:capacity];
    const unsigned char *dataBuffer = data.bytes;
    for (NSUInteger i = 0; i < data.length; ++i) {
        [stringBuffer appendFormat:@"%02X", (unsigned int)dataBuffer[i]];
    }
    return [stringBuffer copy];
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
    NSLog(@"TalkingData: openURL:%@", url);
    
    /*
     1、跳出APP外部在 safari 中打开，type=5,url=要打开的链接：
     {"type":"5","url":"https://lamapi.chwxkj.top"}
     
     2、内部H5跳转，type=15,url=要打开的链接：
     {"type":"15","url":"https://lamapi.chwxkj.top"}
     
     3、重新获取消息未读数 type=999996：
     {"type":"999996"}
     
     4、隐藏底部bar type=999997：
     {"type":"999997"}
     
     5、显示底部bar type=999998：
     {"type":"999998"}
     
     6、TD统计埋点 type=999999，两个参数：
     {"type":"999999","task_title":"TD统计的事件名","task_label":"点击要统计的按钮"}
     */
    
    NSString *urlString = [url.absoluteString stringByRemovingPercentEncoding];
    if ([urlString hasPrefix:@"lamapiapp.com"]) {
        NSArray *result = [urlString componentsSeparatedByString:@"lamapiapp.com://"];
        if(result.count > 1){
            NSString *value = result[1];
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[value dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
            [_channel invokeMethod:@"parseScheme" arguments:dict];
        }
    }
    
    return YES;
}

@end
